package com.bnzj.core.util;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

@Component
public class SpringUtils implements ApplicationContextAware, BeanFactoryAware {
    private static ApplicationContext applicationContext;
    
    private static BeanFactory beanFactory;
    
    private static Environment environment;
    
    private static synchronized void setEnv(Environment environment) {
        SpringUtils.environment = environment;
    }
    
    private static synchronized void setApp(ApplicationContext applicationContext) {
        SpringUtils.applicationContext = applicationContext;
    }
    
    private static synchronized void setBF(BeanFactory beanFactory) {
        SpringUtils.beanFactory = beanFactory;
    }
    
    public static void setEnvironment(Environment environment) {
        if(SpringUtils.environment == null) {
            setEnv(environment);
        }
    }

    /**
     * @param applicationContext the applicationContext to set
     */
    public void setApplicationContext(ApplicationContext applicationContext) {
    	setApp(applicationContext);
    }

    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        setBF(beanFactory);
    }
    
    public static void registerSingleton(String beanName, Object singletonObject) {
        if (beanFactory != null && beanFactory instanceof ConfigurableBeanFactory) {
            ((ConfigurableBeanFactory)beanFactory).registerSingleton(beanName, singletonObject);
        }
    }
    
    public static String getProperty(String key) {
        return environment.getProperty(key);
    }
    
    public static String getProperty(String key, String defaultValue) {
        return environment.getProperty(key, defaultValue);
    }
    
    @SuppressWarnings("unchecked")
	public static <T> T get(String name){
        return (T)applicationContext.getBean(name);
    }
    
    public static <T> T get(String name, Class<T> clz){
        return applicationContext.getBean(name, clz);
    }
    
    public static <T> T get(Class<T> clz){
        return applicationContext.getBean(clz);
    }
}
